package com.joint.web.action.party;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.RoleService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.*;
import com.joint.core.entity.AnnualBudget;
import com.joint.core.service.*;
import com.joint.core.service.AnnualBudgetService;
import com.joint.web.action.BaseFlowAction;
import com.opensymphony.xwork2.ActionContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxAnnualbudgetAction extends BaseFlowAction {
   
    @Resource
    private AnnualBudgetService annualBudgetService;
    @Resource
    private AnnualBudgetDetailService annualBudgetDetailService;
    @Resource
    private MoneyAvgDetailService moneyAvgDetailService;
    @Resource
    private RebateActivityDetailService rebateActivityDetailService;
    @Resource
    private RebateActivityService rebateActivityService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;
    @Resource
    private TaskRecordService taskRecordService;

    private AnnualBudget annualBudget;
    private List<Map<String,Object>> postArrayList;

    private int numStatus;
    private Users loginUser;

    //前台传到后台的数据
    private String str;
    private String departId;
    private String annualBudgetItemId;/**/
    private List<Dict> dictList;
    private List<Double> doubles;


    private String  budgetMoney;//前台传回的字符串
    private BigDecimal [] budgetMoneyArray;//定义数组 ，将字符串转化为数组

    private String remark;
    private List<String> remarkArray;

   // private AnnualBudgetDetail annualBudgetDetail;

    //从后台传回前台的数据




    /**
     * 申请的年份
     */
    private String annualBudgetYear;
    /**
     * 所属单位
     */
    private Department department;
    /**
     *申请预算详情
     */
    private List<AnnualBudgetDetail> annualBudgetDetailList;
    /**
     * 年度预算金额
     */
    private BigDecimal annualBudgetMoney;

    private String viewtype;
    private String annualBudgetDetailId;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "annualbudget";
    }
    public String checkCount(){
        department=new Department();
        pager = new Pager(0);
        if (rows <= 0){
           rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(departId)){
            department=departmentService.get(departId.trim());
            params.put("department",department);
        }
        params.put("processState",new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
        String date=sdf.format(new Date());
        params.put("annualBudgetYear",date);
        pager=annualBudgetService.findByPager(pager,params);

        List<AnnualBudget> annualBudgetsList;
        if (pager.getTotalCount() > 0){
            annualBudgetsList = (List<AnnualBudget>) pager.getList();
        }else{
            annualBudgetsList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        if(annualBudgetsList.size()>0){
            data.put("count",annualBudgetsList.size());
        }else{
            data.put("count",0);
        }

        /*for(AnnualBudget annualBudget:annualBudgetsList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap = new HashMap<String,Object>();
            rMap.put("id",annualBudget.getId()!=null?annualBudget.getId():"");
            if(annualBudget.getCreateDate()!=null){
                String year=new SimpleDateFormat("yyyy").format(annualBudget.getCreateDate());
                rMap.put("year",year);
            }else{
                rMap.put("year","");
            }
            rMap.put("departmentName",annualBudget.getDepartment()!=null?annualBudget.getDepartment().getName():"");
            rMap.put("annualBudgetMoney",annualBudget.getAnnualBudgetMoney()!=null?annualBudget.getAnnualBudgetMoney():"");
            rMap.put("creater",annualBudget.getCreater()!=null?annualBudget.getCreater().getName():"");
            rMap.put("date",annualBudget.getCreateDate()!=null?new SimpleDateFormat("yyyy-MM-dd").format(annualBudget.getCreateDate()):"");
            rMap.put("state",annualBudget.getProcessState().value()!=null?annualBudget.getProcessState().value():"");




            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }*/

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& org.apache.commons.lang3.StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(org.apache.commons.lang3.StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){

                                    switch (field){
                                        /*case "year":
                                            params.put("createDate", DataUtil.StringToDate(rule.getString("data"),"yyyy"));
                                            break;*/
                                        case "annualBudgetMoney":
                                            params.put("annualBudgetMoney", new BigDecimal(rule.getString("data")));
                                            break;
                                        default:
                                                params.put(field, rule.getString("data"));
                                    }
                                    /*if(field.equals("createDate")){
                                        params.put("createDate", DataUtil.StringToDate(rule.getString("data")));
                                    }
                                    else {
                                        params.put(field, rule.getString("data"));
                                    }*/
                                }
                            }
                        }
                    }

                }
            }
        }

        return params;
    }
    public String count(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        String annualBudgetYear=new SimpleDateFormat("yyyy").format(new Date());
        params.put("annualBudgetYear",annualBudgetYear);
        if(StringUtils.isNotEmpty(departId)){
            department=departmentService.get(departId);
            params.put("department",department);
        }

        pager=annualBudgetService.findByPagerAndFinish("annualbudget",pager,params);

        List<AnnualBudget> annualBudgetsList;
        if (pager.getTotalCount() > 0){
            annualBudgetsList = (List<AnnualBudget>) pager.getList();
        }else{
            annualBudgetsList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(AnnualBudget annualBudget:annualBudgetsList){
            if(annualBudget.getAnnualBudgetDetailList()!=null){
                List<AnnualBudgetDetail> annualBudgetDetails=annualBudget.getAnnualBudgetDetailList();
                for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetails){
                    rMap = new HashMap<String,Object>();
                    rMap.put("id",annualBudgetDetail.getId()!=null?annualBudgetDetail.getId():"");
                    rMap.put("annualBudgetId",annualBudget.getId()!=null?annualBudget.getId():"");
                    rMap.put("dictName",annualBudgetDetail.getAnnualBudgetItem()!=null?annualBudgetDetail.getAnnualBudgetItem().getName():"");
                    rMap.put("annualBudgetMoney",annualBudgetDetail.getBudgetMoney()!=null?annualBudgetDetail.getBudgetMoney():"");
                    JSONObject o = JSONObject.fromObject(rMap);
                    dataRows.add(o);
                }

            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String listfordialog(){
        department=new Department();
        annualBudget=new AnnualBudget();
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        String annualBudgetYear=new SimpleDateFormat("yyyy").format(new Date());
        params.put("annualBudgetYear",annualBudgetYear);
        if(StringUtils.isNotEmpty(departId)){
            department=departmentService.get(departId);
            params.put("department",department);
        }
      params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        List<AnnualBudgetDetail> annualBudgetDetailList=Lists.newArrayList();
        if(StringUtils.isNotEmpty(str)){
            for(String s:str.split(",")){
                AnnualBudgetDetail annualBudgetDetail=annualBudgetDetailService.get(s.trim());
                annualBudgetDetailList.add(annualBudgetDetail);
            }
        }

        //pager=annualBudgetService.findByPagerAndFinish("annualbudget",pager,params);
       pager=annualBudgetService.findByPager(pager,params);

        List<AnnualBudget> annualBudgetsList;
        if (pager.getTotalCount() > 0){
            annualBudgetsList = (List<AnnualBudget>) pager.getList();
        }else{
            annualBudgetsList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        List<AnnualBudgetDetail> annualBudgetDetailList1=Lists.newArrayList();
        for(AnnualBudget annualBudget:annualBudgetsList){
            List<AnnualBudgetDetail> annualBudgetDetailList2=annualBudget.getAnnualBudgetDetailList();
                  for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList2){
                      annualBudgetDetailList1.add(annualBudgetDetail);
                  }
        }
        if(annualBudgetDetailList!=null){
            annualBudgetDetailList1.removeAll(annualBudgetDetailList);
        }

        for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList1){
            rMap = new HashMap<String,Object>();
            rMap.put("id",annualBudgetDetail.getId()!=null?annualBudgetDetail.getId():"");
            rMap.put("dictName",annualBudgetDetail.getAnnualBudgetItem()!=null?annualBudgetDetail.getAnnualBudgetItem().getName():"");
            rMap.put("annualBudgetMoney",annualBudgetDetail.getBudgetMoney()!=null?annualBudgetDetail.getBudgetMoney():"");
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=annualBudgetService.findByPagerAndLimit(false, "annualbudget", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=annualBudgetService.findByPagerAndFinish("annualbudget", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=annualBudgetService.findByPagerAndLimit(true, "annualbudget", pager, params);
        }

        List<AnnualBudget> annualBudgetsList;
        if (pager.getTotalCount() > 0){
            annualBudgetsList = (List<AnnualBudget>) pager.getList();
        }else{
            annualBudgetsList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(AnnualBudget annualBudget:annualBudgetsList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap = new HashMap<String,Object>();
            rMap.put("id",annualBudget.getId()!=null?annualBudget.getId():"");
            rMap.put("annualBudgetYear",annualBudget.getAnnualBudgetYear()!=null?annualBudget.getAnnualBudgetYear():"");
            /*if(annualBudget.getCreateDate()!=null){
                String year=new SimpleDateFormat("yyyy").format(annualBudget.getCreateDate());
                rMap.put("year",year);
            }else{
                rMap.put("year","");
            }*/
            rMap.put("departmentName",annualBudget.getDepartment()!=null?annualBudget.getDepartment().getName():"");
            rMap.put("annualBudgetMoney",annualBudget.getAnnualBudgetMoney()!=null?annualBudget.getAnnualBudgetMoney():"");
            rMap.put("creater",annualBudget.getCreater()!=null?annualBudget.getCreater().getName():"");
            rMap.put("date",annualBudget.getCreateDate()!=null?new SimpleDateFormat("yyyy-MM-dd").format(annualBudget.getCreateDate()):"");
            rMap.put("state",annualBudget.getProcessState().value()!=null?annualBudget.getProcessState().value():"");




            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){

        department=new Department();
        annualBudgetDetailList=Lists.newArrayList();

        if(StringUtils.isNotEmpty(keyId)) {
            loginUser=usersService.getLoginInfo();
            annualBudget = annualBudgetService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            //部门对象
            if(annualBudget.getDepartment()!=null){
                department=annualBudget.getDepartment();
            }
            //年度预算详情对象
            if(annualBudget.getAnnualBudgetDetailList()!=null){
                annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
            }

        }
        return "read";
    }

    public String input(){
        department=new Department();
        annualBudgetDetailList=Lists.newArrayList();
        if (StringUtils.isNotEmpty(keyId)){

            annualBudget = annualBudgetService.get(keyId);
            loginUser=usersService.getLoginInfo();
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            //部门对象
            if(annualBudget.getDepartment()!=null){
                department=annualBudget.getDepartment();
            }
            //年度预算详情对象
            if(annualBudget.getAnnualBudgetDetailList()!=null){
                annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
            }
            //申请人信息




        } else {
        }




        return "input";
    }

    private void setData(){

        doubles=Lists.newArrayList();
        annualBudgetDetailList=Lists.newArrayList();
        department=new Department();
        dictList=Lists.newArrayList();
        remarkArray=Lists.newArrayList();
        Company company=usersService.getLoginInfo().getCompany();
        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            annualBudget = annualBudgetService.get(keyId);


        }else{
            annualBudget = new AnnualBudget();
            annualBudget.setCreater(usersService.getLoginInfo());

        }
               //所选单位
        if(StringUtils.isNotEmpty(departId)) {
            department = departmentService.get(departId);
        }
        //年度预算
        if(StringUtils.isNotEmpty(annualBudgetItemId)){
            for(String s:annualBudgetItemId.split(",")){
                dictList.add(dictService.get(s.trim()));
            }
        }
        //预算金额
        if(StringUtils.isNotEmpty(budgetMoney)){
            for(String s:budgetMoney.split(",")){
                doubles.add(Double.parseDouble(s.trim()));
            }
        }
        //备注
        if(StringUtils.isNotEmpty(remark)){
           for(String s:remark.split(",")){
               remarkArray.add(s.trim());
           }
        }
        /*//年度预算申请对象
        if(StringUtils.isNotEmpty(annualBudgetDetailId)){
            for(String s:annualBudgetDetailId.split(",")){
                annualBudgetDetailList1.add(annualBudgetDetailService.get(s.trim()));
            }

        }
        if(StringUtils.isNotEmpty(annualBudgetDetailId)){
            for(int i=0;i<annualBudgetDetailList1.size();i++){
                AnnualBudgetDetail annualBudgetDetail=annualBudgetDetailList1.get(i);
                annualBudgetDetail.setAnnualBudgetItem(annualBudgetItemArray[i]);
                annualBudgetDetail.setBudgetMoney(doubles.get(i));
                annualBudgetDetail.setUsedMoney(0.0);
                annualBudgetDetail.setEnableMoney(0.0);
                annualBudgetDetail.setRemark(remarkArray[i]);
                annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                annualBudgetDetailService.update(annualBudgetDetail);
            }

        }else{
            for(int i=0;i<doubles.size();i++){
                AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                annualBudgetDetail.setAnnualBudgetItem(annualBudgetItemArray[i]);
                annualBudgetDetail.setBudgetMoney(doubles.get(i));
                annualBudgetDetail.setCompany(company);
                annualBudgetDetail.setUsedMoney(0.0);
                annualBudgetDetail.setEnableMoney(0.0);
                annualBudgetDetail.setRemark(remarkArray[i]);
                annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                annualBudgetDetailService.save(annualBudgetDetail);
                annualBudgetDetailList.add(annualBudgetDetail);
            }
        }
*/
        annualBudgetYear=new SimpleDateFormat("yyyy").format(new Date());
        annualBudget.setCreateDate(new Date());
        annualBudget.setCompany(usersService.getLoginInfo().getCompany());
        annualBudget.setAnnualBudgetYear(annualBudgetYear);
        annualBudget.setDepartment(department);
        annualBudget.setAnnualBudgetMoney(annualBudgetMoney);
    }

    // 保存
    public String save(){
        setData();
        Company company=usersService.getLoginInfo().getCompany();

        int len=dictList.size();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                annualBudget=annualBudgetService.get(keyId);
                if(StringUtils.isNotEmpty(annualBudgetDetailId)){
                    annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
                    for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList){
                        annualBudgetDetailService.delete(annualBudgetDetail);
                    }
                    annualBudget.setAnnualBudgetDetailList(null);
                    List<AnnualBudgetDetail> annualBudgetDetailList1=Lists.newArrayList();
                    for(int i=0;i<len;i++){
                        AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                        annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                        annualBudgetDetail.setBudgetMoney(doubles.get(i));
                        annualBudgetDetail.setRemark(remarkArray.get(i));
                        annualBudgetDetail.setAnnualBudget(annualBudget);
                        annualBudgetDetail.setCompany(company);
                        annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                        annualBudgetDetailService.save(annualBudgetDetail);
                        annualBudgetDetailList1.add(annualBudgetDetail);
                    }
                    annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList1);
                    annualBudgetService.update(annualBudget);



                    /*for(String s:annualBudgetDetailId.split(",")){
                        annualBudgetDetailList.add(annualBudgetDetailService.get(s.trim()));
                    }
                    for(int i=0;i<len;i++){
                        AnnualBudgetDetail annualBudgetDetail=annualBudgetDetailList.get(i);
                        annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                        annualBudgetDetail.setBudgetMoney(doubles.get(i));
                        annualBudgetDetail.setRemark(remarkArray.get(i));
                        annualBudgetDetail.setAnnualBudget(annualBudget);
                        annualBudgetDetail.setCompany(company);
                        annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                        annualBudgetDetailService.update(annualBudgetDetail);
                        annualBudgetDetailList.add(annualBudgetDetail);
                    }
                    annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList);
                    annualBudgetService.update(annualBudget);*/
                }else{
                    annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
                    for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList){
                        annualBudgetDetailService.delete(annualBudgetDetail);
                    }
                    annualBudget.setAnnualBudgetDetailList(null);
                    List<AnnualBudgetDetail> annualBudgetDetailList1=Lists.newArrayList();
                    for(int i=0;i<len;i++){
                        AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                        annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                        annualBudgetDetail.setBudgetMoney(doubles.get(i));
                        annualBudgetDetail.setRemark(remarkArray.get(i));
                        annualBudgetDetail.setAnnualBudget(annualBudget);
                        annualBudgetDetail.setCompany(company);
                        annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                        annualBudgetDetailService.save(annualBudgetDetail);
                        annualBudgetDetailList1.add(annualBudgetDetail);
                    }
                    annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList1);
                    annualBudgetService.update(annualBudget);
                }
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                String id=annualBudgetService.save(annualBudget, "annualbudget", various);
                annualBudget=annualBudgetService.get(id);
                for(int i=0;i<len;i++){
                    AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                    annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                    annualBudgetDetail.setBudgetMoney(doubles.get(i));
                    annualBudgetDetail.setRemark(remarkArray.get(i));
                    annualBudgetDetail.setAnnualBudget(annualBudget);
                    annualBudgetDetail.setCompany(company);
                    annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                    annualBudgetDetailService.save(annualBudgetDetail);
                    annualBudgetDetailList.add(annualBudgetDetail);
                }
                annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList);
                annualBudgetService.update(annualBudget);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Company company=usersService.getLoginInfo().getCompany();

        int len=dictList.size();
        if(StringUtils.isNotEmpty(keyId)){
            annualBudget=annualBudgetService.get(keyId);
            annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
            for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList){
                annualBudgetDetailService.delete(annualBudgetDetail);
            }
            annualBudget.setAnnualBudgetDetailList(null);
            List<AnnualBudgetDetail> annualBudgetDetailList1=Lists.newArrayList();
            for(int i=0;i<len;i++){
                AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                annualBudgetDetail.setBudgetMoney(doubles.get(i));
                annualBudgetDetail.setRemark(remarkArray.get(i));
                annualBudgetDetail.setAnnualBudget(annualBudget);
                annualBudgetDetail.setCompany(company);
                annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                annualBudgetDetailService.save(annualBudgetDetail);
                annualBudgetDetailList1.add(annualBudgetDetail);
            }
            annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList1);
            annualBudgetService.update(annualBudget);
        }else{
           annualBudgetService.save(annualBudget);
            for(int i=0;i<len;i++){
                AnnualBudgetDetail annualBudgetDetail=new AnnualBudgetDetail();
                annualBudgetDetail.setAnnualBudgetItem(dictList.get(i));
                annualBudgetDetail.setBudgetMoney(doubles.get(i));
                annualBudgetDetail.setRemark(remarkArray.get(i));
                annualBudgetDetail.setAnnualBudget(annualBudget);
                annualBudgetDetail.setCompany(company);
                annualBudgetDetail.setState(BaseEnum.StateEnum.Enable);
                annualBudgetDetailService.save(annualBudgetDetail);
                annualBudgetDetailList.add(annualBudgetDetail);
            }
            annualBudget.setAnnualBudgetDetailList(annualBudgetDetailList);
            annualBudgetService.update(annualBudget);
        }


        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        Set<Duty> dutySet= null;
        ArrayList<Department> departmentArrayList=null;
        dutySet=usersService.getLoginInfo().getDutySet();

       /* loop1:for(Duty duty:dutySet){
            Post post = duty.getPost();//根据当前登录用户的职责，得到当前登陆用户的岗位
            if(StringUtils.equals(post.getName(),"退管会专员")  == false){
                continue;//进入当前登录人的下一个职权
            }
            Department dept = duty.getDepartment().getParent();//根据当前登陆人的职责，得到当前人的部门的上级部门
            if (dept == null) {//上级部门为空的话，进入当前人的下一个职责
                continue;
            }
            Set<Power> powers = dept.getPowerSet();//获取当前登陆人的职责，得到部门的部门的职权集合
            loop2:for(Power power:powers){//遍历姥姥级部门下的所有职权
                //   LogUtil.info("power:"+power.getId());
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记") == true) {
                    List<Users> usersList=dutyService.getPersons(dept, post1);//更具岗位对象获取该部门下的指定岗位下的 所有人
                    for(Users users1:usersList){
                        LogUtil.info("userName:"+users1.getName());
                        list.add(users1.getId());
                    }
                    break loop1;
                }
            }
        }
        var2.put("approvers",list);*/
        if(org.apache.commons.lang.StringUtils.isNotEmpty(departId)){

            department=departmentService.get(departId);
            Set<Power> powers = department.getPowerSet();
            for(Power power:powers){
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记")==true){
                    List<Users> usersList=dutyService.getPersons(department, post1);
                    for(Users users1:usersList){
                        list.add(users1.getId());
                    }
                }
            }
            var2.put("approvers",list);
        }
        if(StringUtils.isEmpty(comment)){
            comment="";
        }

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                annualBudgetService.approve(annualBudget, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                annualBudgetService.commit(annualBudget, "annualbudget", var1, var2, curDutyId);/*返回文档的iD*/
                /*LogUtil.info("KeyId_2 = "+keyId);
                AnnualBudget entity = annualBudgetService.get(keyId);*//*文档id*//*
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                annualBudgetService.save(entity);*/


            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        annualBudget = annualBudgetService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

       // var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {

                annualBudgetService.approve(annualBudget, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
                Task overtask=workflowService.getCurrentTask(keyId);
                if(overtask==null){

                    AnnualBudget entity=annualBudgetService.get(keyId);
                    entity.setProcessState(FlowEnum.ProcessState.Finished);
                    annualBudgetService.update(entity);

                    List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
                    for(TaskRecord taskRecord:taskRecords){
                        taskRecord.setType(2);
                        taskRecordService.update(taskRecord);
                    }
                }else{
                    if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){
                        runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                    }
                }



                /*annualBudget=new AnnualBudget();
                annualBudget=annualBudgetService.get(keyId);
                Double applyMoney=new Double(0.0);
                Department department=new Department();
                if(annualBudget.getAnnualBudgetDetailList()!=null){
                    department=annualBudget.getDepartment();
                    List<AnnualBudgetDetail> annualBudgetDetailList=annualBudget.getAnnualBudgetDetailList();
                    for(AnnualBudgetDetail annualBudgetDetail:annualBudgetDetailList){
                        applyMoney+=Double.parseDouble(annualBudgetDetail.getBudgetMoney());
                    }
                }
                Company com = usersService.getCompanyByUser();
                loginUser = usersService.getLoginInfo();

                Map<String,Object> params = new HashMap<String,Object>();
                params = getSearchFilterParams(_search,params,filters);

                params.put("company",com);
                params.put("state",BaseEnum.StateEnum.Enable);
                if(department!=null){
                    params.put("department",department);
                }
                String avgYear=new SimpleDateFormat("yyyy").format(new Date());
                params.put("avgYear",avgYear);
                List<MoneyAvgDetail> moneyAvgDetailList=moneyAvgDetailService.getList(params);
                if(moneyAvgDetailList!=null){
                    for(MoneyAvgDetail moneyAvgDetail:moneyAvgDetailList){
                        moneyAvgDetail.setDepartEveryUseDetail(moneyAvgDetail.getDepartEveryUseDetail()+applyMoney);
                        moneyAvgDetail.setDepartResidueEnableMoney(moneyAvgDetail.getDepartResidueEnableMoney()-applyMoney);
                        moneyAvgDetailService.save(moneyAvgDetail);
                    }
                }*/
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        annualBudget = annualBudgetService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        //  var2.put("curDutyId", curDutyId);
        try {
            annualBudgetService.approve(annualBudget, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        annualBudget = annualBudgetService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        var2.put("curDutyId", curDutyId);
        //  var2.put("curDutyId", curDutyId);
        try {
            annualBudgetService.approve(annualBudget, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            annualBudget = annualBudgetService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("annualbudget");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            annualBudgetService.reject(annualBudget, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            annualBudget = annualBudgetService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("annualbudget");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            annualBudgetService.deny(annualBudget, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public AnnualBudget getAnnualBudget() {
        return annualBudget;
    }

    public void setAnnualBudget(AnnualBudget annualBudget) {
        this.annualBudget = annualBudget;
    }











    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }


    public String getViewtype() {


        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public List<Map<String, Object>> getPostArrayList() {
        return postArrayList;
    }

    public void setPostArrayList(List<Map<String, Object>> postArrayList) {
        this.postArrayList = postArrayList;
    }




    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getAnnualBudgetItemId() {
        return annualBudgetItemId;
    }

    public void setAnnualBudgetItemId(String annualBudgetItemId) {
        this.annualBudgetItemId = annualBudgetItemId;
    }



    public String getBudgetMoney() {
        return budgetMoney;
    }

    public void setBudgetMoney(String budgetMoney) {
        this.budgetMoney = budgetMoney;
    }

    public BigDecimal[] getBudgetMoneyArray() {
        return budgetMoneyArray;
    }

    public void setBudgetMoneyArray(BigDecimal[] budgetMoneyArray) {
        this.budgetMoneyArray = budgetMoneyArray;
    }

    public String getAnnualBudgetYear() {
        return annualBudgetYear;
    }

    public void setAnnualBudgetYear(String annualBudgetYear) {
        this.annualBudgetYear = annualBudgetYear;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }





    public List<AnnualBudgetDetail> getAnnualBudgetDetailList() {
        return annualBudgetDetailList;
    }

    public void setAnnualBudgetDetailList(List<AnnualBudgetDetail> annualBudgetDetailList) {
        this.annualBudgetDetailList = annualBudgetDetailList;
    }

    public BigDecimal getAnnualBudgetMoney() {
        return annualBudgetMoney;
    }

    public void setAnnualBudgetMoney(BigDecimal annualBudgetMoney) {
        this.annualBudgetMoney = annualBudgetMoney;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public String getAnnualBudgetDetailId() {
        return annualBudgetDetailId;
    }

    public void setAnnualBudgetDetailId(String annualBudgetDetailId) {
        this.annualBudgetDetailId = annualBudgetDetailId;
    }

    public List<Dict> getDictList() {
        return dictList;
    }

    public void setDictList(List<Dict> dictList) {
        this.dictList = dictList;
    }

    public List<Double> getDoubles() {
        return doubles;
    }

    public void setDoubles(List<Double> doubles) {
        this.doubles = doubles;
    }

    public List<String> getRemarkArray() {
        return remarkArray;
    }

    public void setRemarkArray(List<String> remarkArray) {
        this.remarkArray = remarkArray;
    }
}


